package com.framework.utils.httpClient;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.Cookie;

import com.framework.utils.DateUtils;
import com.framework.utils.jiufu.StringUtils;
import com.framework.utils.json.JsonUtils;
import com.framework.utils.string.StringUtil;
import com.framework.view.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class HttpClean {
	//卡友查询商户号地址 GET请求
	public final static  String QUERY_MERCHANT_URL = "https://vip.cardinfo.com.cn/agent/orderDetail.action?id=";
	//卡友查询posSN地址 POST请求
	public final static  String QUERY_POST_SN_URL = "https://vip.cardinfo.com.cn/agent/newPosQuery.action";

	//开店宝查询商户号地址 GET请求
	public final static  String KAI_QUERY_MERCHANT_URL = "https://v.91dbq.com/agent/orderDetail.action?id=";
	//开店宝查询posSN地址 POST请求
	public final static  String KAI_QUERY_POST_SN_URL = "https://v.91dbq.com/agent/posQuery.action";

	/*
	  * 处理https GET/POST请求 
	  * 请求地址、请求方法、参数 
	  * */  
	 public static String httpsRequest(String requestUrl,String requestMethod,String outputStr,String JsessionId){  
	     StringBuffer buffer=null;  
	     try{  
	     //创建SSLContext  
	     SSLContext sslContext=SSLContext.getInstance("SSL");
	     TrustManager[] tm={new MyX509TrustManager()};
	     //初始化  
	     sslContext.init(null, tm, new java.security.SecureRandom());
             //获取SSLSocketFactory对象
	     SSLSocketFactory ssf = sslContext.getSocketFactory(); 
	     URL url=new URL(requestUrl);  
	     HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
	     conn.setRequestProperty("Cookie", JsessionId);
	     conn.setDoOutput(true);  
	     conn.setDoInput(true);  
	     conn.setUseCaches(false);  
	     conn.setRequestMethod(requestMethod);  
	     //设置当前实例使用的SSLSoctetFactory  
	     conn.setSSLSocketFactory(ssf);  
	     conn.connect();  
	     //往服务器端写内容  
	     if(null!=outputStr){  
	         OutputStream os=conn.getOutputStream();  
	         os.write(outputStr.getBytes(StandardCharsets.UTF_8));
	         os.close();  
	     }
	     //读取服务器端返回的内容  
	     InputStream is=conn.getInputStream();  
	     InputStreamReader isr=new InputStreamReader(is, StandardCharsets.UTF_8);
	     BufferedReader br=new BufferedReader(isr);  
	     buffer=new StringBuffer();  
	     String line=null;  
	     while((line=br.readLine())!=null){  
	         buffer.append(line);  
	     }  
	     }catch(Exception e){  
	         e.printStackTrace();  
	     }
	     return buffer.toString();  
	 }


 	 /**
     * 解决随行付超时问题
     * @param date 日期
     * @param k 第几页
     * @param sessionId 网站sessionId
     * @return
     */
    public static Elements getData(String date,int k,String sessionId){
		String requestUrl = "https://vip.cardinfo.com.cn/agent/orderQuery.action?amountStart=&authorizationCode=&pagingPage="+ k +"&createTimeEnd="+ date +"&cardType=&externalId=&createTimeStart="+ date +"&radio=on&amountEnd=&customerType=iCust&sortColumn=id&sortColumn=id&sortDirection=-1&transType=&panEnd=&customerNo=&posCati=&status=SETTLED%2CSUCCESS&transWay=&secondAgentName=";
		String  repost =  httpsRequest(requestUrl,"POST",null, sessionId);
		Document doc = Jsoup.parse(repost);
		Elements trs = doc.select("table").select("tr");
		if(trs.size() <= 0){
			Thread thread = Thread.currentThread();
			try {
				Thread.sleep(5000);
				trs = getData(date, k, sessionId);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}//暂停1.5秒后程序继续执行
		}
		return trs;
    }

	/**
	 * 卡友根据新的sn查询post机器码
	 */
	public static String querKayouPosSn(String id,String sessionId){
		Thread thread = Thread.currentThread();
		String postSn = null;
		try {
			Thread.sleep(5000);
			String  res =  httpsRequest(QUERY_MERCHANT_URL+id,"GET",null, sessionId);
			Document doc = Jsoup.parse(res);
			Elements trs = doc.select("table").select("tr");
			Elements tds = trs.get(0).select("td");
			String merchantCode = tds.get(0).text();
			if(StringUtils.isNotNull(merchantCode) && StringUtils.isNotBlank(merchantCode)){
				Thread.sleep(5000);
				//拼接查询PosSn的参数
				String parms = "pos.querySource=YOUSHUA&pos.posSn=&pos.customerNo="+merchantCode+"&pos.directAgentNo=&pos.status";
				String  repost =  httpsRequest(QUERY_POST_SN_URL,"POST",parms, sessionId);
				Document docPost = Jsoup.parse(repost);
				Elements trsPost = docPost.select("table").select("tr");
				Elements tdsPost = trsPost.get(1).select("td");
				postSn = tdsPost.get(1).text();
				System.out.print(postSn);
				return postSn;
			}else{
				return null;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}//暂停1.5秒后程序继续执行
		return postSn;
	}


	/**
	 * 解决开店宝超时问题
	 * @param date 日期
	 * @param k 第几页
	 * @param sessionId 网站sessionId
	 * @return
	 */
	public static Elements getKaiDianBaoData(String date,int k,String sessionId){
		String requestUrl = "https://v.91dbq.com/agent/orderQuery.action?createTimeStart="+date+"&createTimeEnd="+date+"&radio=on&posCati=&panEnd=&cardType=CREDIT_CARD&customerNo=&externalId=&status=SETTLED,SUCCESS&transType=PURCHASE&actTransStyle=&authorizationCode=&amountStart=&amountEnd=&secondAgentName=&customerType=bigCust&pagingPage="+k;
		String  repost =  httpsRequest(requestUrl,"POST",null, sessionId);
		Document doc = Jsoup.parse(repost);
		Elements trs = doc.select("table").select("tr");
		if(trs.size() <= 0){
			Thread thread = Thread.currentThread();
			try {
				Thread.sleep(5000);
				trs = getData(date, k, sessionId);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}//暂停1.5秒后程序继续执行
		}
		return trs;
	}

	/**
	 * 开店宝根据新的sn查询post机器码
	 */
	public static String querKaiDianBaoPosSn(String id,String sessionId){
		Thread thread = Thread.currentThread();
		String postSn = null;
		try {
			Thread.sleep(5000);
			String  res =  httpsRequest(KAI_QUERY_MERCHANT_URL+id,"GET",null, sessionId);
			Document doc = Jsoup.parse(res);
			Elements trs = doc.select("table").select("tr");
			Elements tds = trs.get(0).select("td");
			String merchantCode = tds.get(0).text();
			if(StringUtils.isNotNull(merchantCode) && StringUtils.isNotBlank(merchantCode)){
				Thread.sleep(5000);
				//拼接查询PosSn的参数
				String parms = "posCati=&posSn=&status=TRANS&useType=&softVersion=&paramVersion=&customerNo="+merchantCode;
				String  repost =  httpsRequest(KAI_QUERY_POST_SN_URL,"POST",parms, sessionId);
				Document docPost = Jsoup.parse(repost);
				Elements trsPost = docPost.select("table").select("tr");
				Elements tdsPost = trsPost.get(1).select("td");
				postSn = tdsPost.get(1).text();
				System.out.print(postSn);
				return postSn.substring(8);
			}else{
				return null;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}//暂停1.5秒后程序继续执行
		return  postSn;
	}


	/**
	 * 查询乐刷交易
	 * @param sessionId
	 * @param date
	 * @param t0Flag 0:(T+1) 1:(T+0)
	 * @return
	 */
	public static List<LeShuaTranView> getLeShuaTranList(String sessionId,String date,Integer t0Flag){
		try{
			String tranUrl = "https://shuabao.yeahka.com/agent-new/agent/trade/info/list";
			String tranParms = "page=1&limit=500&queryBeginTime="+date+"&queryEndTime="+date+"&t0Flag="+t0Flag+"&payType=1&state=5";
			//商户查询地址
			String res = HttpClean.httpsRequest(tranUrl,"POST",tranParms, sessionId);
			if(res == null){
				return null;
			}
			Map<String,Object> map = JsonUtils.fromJson(res);
			String code = map.get("code").toString();
			if(StringUtils.equals("0",code)){
				String dataMap = map.get("data").toString();
				if(StringUtils.isNotBlank(dataMap)){
					return JsonUtils.jsonToList(dataMap,LeShuaTranView.class);
				}
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * 查询乐刷VIP数据
	 * @param sessionId
	 * @param date
	 * @return
	 */
	public static List<LeShuaVipView> getLeShuaVipList(String sessionId,String date){
		try{
			String vipUrl = "https://shuabao.yeahka.com/agent-new/agent/merchant/vip/list";
			String tranParms = "page=1&limit=500&queryBeginTime="+date+"&queryEndTime="+date;
			//商户查询地址
			String res = HttpClean.httpsRequest(vipUrl,"POST",tranParms, sessionId);
			if(res == null){
				return null;
			}
			Map<String,Object> map = JsonUtils.fromJson(res);
			String code = map.get("code").toString();
			if(StringUtils.equals("0",code)){
				String dataMap = map.get("data").toString();
				if(StringUtils.isNotBlank(dataMap)){
					return JsonUtils.jsonToList(dataMap,LeShuaVipView.class);
				}
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * 乐刷大POS交易
	 * @param sessionId
	 * @param date
	 * @return
	 */
	public static List<LeShuaTranBigView> getLeShuaBigList(String sessionId, String date){
		try{
			String vipUrl = "https://ykagent.yeahka.com//ykagent/statistic/queryTradeOrderList.do";
			String tranParms = "pageNum=1&pageSize=1000&token="+sessionId+"&startTime="+date+"&endTime="+date+"&posCati=&panEnd=&orderId=&cardType=2&customerNo=&customerName=&status=SUCCESS&agentNo=&settleStatus=-1";
			//商户查询地址
			String res = HttpClean.httpsRequest(vipUrl,"GET",tranParms, sessionId);
			System.out.print("乐刷大POS查询返回=================="+res);
			if(res == null){
				return null;
			}
			Map<String,Object> map = JsonUtils.fromJson(res);
			String code = map.get("code").toString();
			if(StringUtils.equals("0",code)){
				String dataMap = map.get("data").toString();
				if(StringUtils.isNotBlank(dataMap)){
					return JsonUtils.jsonToList(dataMap,LeShuaTranBigView.class);
				}
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * 查询瑞和宝数据
	 * @param sessionId
	 * @param date
	 * @return
	 */
	public static List<RuiHeBaoView> getRuiHeBaoList(String sessionId, String date){
		try{
			String vipUrl = "https://mpos.ruiyinxin.com/qtfr/deal/deal.do?method=getDealdetail";
			String tranParms = "yearmonthdatestart="+date+"&yearmonthdateend="+date+"&agencySelect=&serialNumber=&terminalcode=&merchantCode=&queryFlag=2&moblieNo=&startValue=&endValue=&customerName=&batchType=&dealType=1&termCode=&bankcard=&page=1&rows=300";
			//商户查询地址
			String res = HttpClean.httpsRequest(vipUrl,"POST",tranParms, sessionId);
			if(res == null){
				return null;
			}
			Map<String,Object> map = JsonUtils.fromJson(res);
			Object rows = map.get("rows");
			if(rows != null){
				String rowsStr = rows.toString();
				return JsonUtils.jsonToList(rowsStr,RuiHeBaoView.class);
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * 查询终端号
	 * @param sessionId
	 * @param posCati
	 * @return
	 */
	public static String queryLeShuaBigMerchantNo(String sessionId, String posCati){
		try{
			String vipUrl = "https://ykagent.yeahka.com//ykagent/pos/queryPosList.do";
			String tranParms = "pageNum=1&pageSize=30&token="+sessionId+"&posCati="+ posCati;
			//商户查询地址
			String res = HttpClean.httpsRequest(vipUrl,"GET",tranParms, sessionId);
			if(res == null){
				return null;
			}
			Map<String,Object> map = JsonUtils.fromJson(res);
			String code = map.get("code").toString();
			if(StringUtils.equals("0",code)){
				String dataMap = map.get("data").toString();
				if(StringUtils.isNotBlank(dataMap)){
					List<LeShuaBigInfoView> list = JsonUtils.jsonToList(dataMap,LeShuaBigInfoView.class);
					if(list.size() > 0){
						return list.get(0).getPosSn();
					}
					return null;
				}
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	public static void main(String[] args) {
		//获取系统的昨天日期
		String date = StringUtil.getDifferDate(-1);
		//String date = "2017-11-22";
		//String dates = "2017-10-30";
		//根据session访问卡友网站
		String res = "https://v.91dbq.com/agent/orderQuery.action?createTimeStart=2019-01-08&createTimeEnd=2019-01-10&radio=on&posCati=&panEnd=&cardType=CREDIT_CARD&customerNo=&externalId=&status=SETTLED,SUCCESS&transType=PURCHASE&actTransStyle=&authorizationCode=&amountStart=&amountEnd=&secondAgentName=&customerType=bigCust";
		String  repost2 =  HttpClean.httpsRequest(res,"POST",null, "JSESSIONID=4AA55E11361B50F1D6ED7E81AD223F7A");
		System.out.print(repost2);

	}


}
